
/* Copyright(C) 1993, The MITRE Corporation */

#import "PhoneSlip.h"
#import "colorView.h"
#import <appkit/appkit.h>
#import <stdio.h>
#import <strings.h>
#include <mach/mach.h>
#include <pwd.h>
#include <sys/types.h>
#include <sys/time.h>

@implementation PhoneSlip

	time_t tp;
	static char *execto[4]={"csh","-f","/tmp/PhoneSlip.to",NULL};
	static char *execlog[4]={"csh","-f","/tmp/PhoneSlip.log",NULL};
	char *user;
	char peoplefile[256] = "";
	char logmailname[256] = "";
	char logfilename[256] = "";
	char soundname[256] = "";
	char checkname[10] = "CHECK  ";
	const char *temp;
	int i, j, pid, ncol, nrow;


- appDidInit:sender
{
/*
	Here we initialize PhoneSlip
*/

/*
	Set the background pink for color machines, gray for mono
*/
	const NXScreen *deepestScreen;
	deepestScreen=[NXApp colorScreen];
	if( deepestScreen->depth == NX_TwoBitGrayDepth)
	    [PMcview setBackgroundGray:NX_LTGRAY]; // Gray Phone Slip
	else
	    [PMcview setBackgroundColor:NXConvertRGBAToColor(1.0 ,0.57 ,0.77 ,1.0)]; // Pink Phone Slip 
	[PMslip display];
	[[PMslip window] makeKeyAndOrderFront:self];
	
/*
	Check for user default file names and use if found
*/
	if(temp = NXReadDefault("PhoneSlip","People"))
	{
	  strcpy(peoplefile,temp);
	  [PMpeople setStringValue:peoplefile];
	  [PMbrowser loadColumnZero];
	}
	[PMbrowser loadColumnZero];
	if(temp = NXReadDefault("PhoneSlip","LogMailname"))
	{
	  strcpy(logmailname,temp);
	  [PMlogmail setStringValue:logmailname];
	}
	if(temp = NXReadDefault("PhoneSlip","LogFilename"))
	{
	  strcpy(logfilename,temp);
	  [PMlogfile setStringValue:logfilename];
	}
	[self setLogMailname:self];
	[self setLogFilename:self];

/*
	Check for user defaults in the check box titles
*/
	[PMchecked getNumRows:&nrow numCols:&ncol];
	for (i=0 ; i<ncol ; i++)
	  for (j=0 ; j<nrow ; j++)
	  {
	    sprintf(&checkname[5],"%1d%1d",i,j);
	    if(temp = NXReadDefault("PhoneSlip",checkname))
	    {
	      [[PMchecked cellAt:j :i] setTitle:temp];
	    }
	    temp = [[PMchecked cellAt:j :i] title];
	    [[PMusercheck cellAt:j :i] setStringValue:temp];
	  }
	
/*
	Set the Time field (will reset later)
*/
	time(&tp);
	[PMtime setStringValue:asctime(localtime(&tp))];
	[PMfor setNextText:PMcaller];	
	[PMcaller setNextText:PMorg];	
	[PMorg setNextText:PMnumber];	
	[PMnumber setNextText:[PMmsg docView]];
		
/*
	Get the users Full name from accounting/password info
*/
	setpwent();
	user = getpwuid((uid_t)getuid())->pw_gecos;
	endpwent();
	[PMsigned setStringValue:user];
	  
/*
	Load the addressee browser
*/
	[PMbrowser setDelegate:self];
	[PMbrowser loadColumnZero];
	[PMbrowser setTarget:self];
	[PMbrowser setAction:@selector(setFor)];
	return self;
}

- send:sender
{
/*
	Performed when user clicks Send
*/

	FILE *PMmail, *PMtemp, *PMlog;
	char *to, msg[4096], toString[100], *address;

/*
	Reset Time field before sending message
*/
	time(&tp);
	[PMtime setStringValue:asctime(localtime(&tp))];

/*
	get addressee
*/
	to = (char *)[PMfor stringValue];
	if(strlen(to) == 0)
	{
	  NXRunAlertPanel("PhoneSlip","No addressee selected", "Sorry", NULL, NULL);
	  return self;
	}
	strcpy(toString,to);
	if (toString[strlen(toString)-1] == '\n')
	  toString[strlen(toString)-1]=0;
	address = strpbrk(toString,"<");
	*(strpbrk(address,">")+1) = 0;
	
/*
	Build message in temporary file from contents of text fields
*/
	[[PMmsg docView] getSubstring:msg start:0 length:[[PMmsg docView] textLength]];
	msg[[[PMmsg docView] textLength]] = 0;
	
	PMtemp = fopen("/tmp/PhoneSlip.msg","w");
	fprintf(PMtemp,"---------------PHONE MESSAGE--------------\n");
	fprintf(PMtemp,"FROM: %s\n",(char *)[PMcaller stringValue]);
	fprintf(PMtemp,"OF: %s\n",(char *)[PMorg stringValue]);
	fprintf(PMtemp,"NUMBER: %s\n\n",(char *)[PMnumber stringValue]);
	for (i=0 ; i<ncol ; i++)
	  for (j=0 ; j<nrow ; j++)
	    if([[PMchecked cellAt:j :i] state])
	      fprintf(PMtemp,"%s\n",[[PMchecked cellAt:j :i] title]);
	fprintf(PMtemp,"%s\n\n",msg);
	fprintf(PMtemp,"SIGNED: %s\n",[PMsigned stringValue]);
	fprintf(PMtemp,"---------------PHONE MESSAGE--------------\n");
	fclose(PMtemp);

/*
	If PRINT is specified in addressee field, print a PS copy of the slip
*/
	if(strstr(to,"PRINT"))
	{
	  [PMslip printPSCode:self];
	}	  
	
/*
	If ONLY is NOT specified in addressee field, use ucb mailer to send
	the message 
*/
	if(!strstr(to,"ONLY"))
	{
	  PMmail = fopen("/tmp/PhoneSlip.to","w");
	  fprintf(PMmail,"/usr/ucb/mail -s 'PHONE SLIP' '%s' </tmp/PhoneSlip.msg\n",address);
	  fclose(PMmail);
	  pid = vfork();
	  if(pid == 0)
	    execve("/bin/csh",execto,NULL);
	}

/*
	If a mail log user name is specified, send a copy to that address also
*/
	if (strlen(logmailname))
	{
	  PMmail = fopen("/tmp/PhoneSlip.log","w");
	  fprintf(PMmail,"/usr/ucb/mail -s 'PhoneSlip for %s' '%s' </tmp/PhoneSlip.msg\n",address,logmailname);
	  fclose(PMmail);
	  pid = vfork();
	  if(pid == 0)
	    execve("/bin/csh",execlog,NULL);
	}

/*
	If a mail log file name is specified, append a copy to the log file
*/
	if (strlen(logfilename))
	{
	  if(PMlog = fopen(logfilename,"a"))
	  {
	    fprintf(PMlog,"TO: %s",(char *)[PMfor stringValue]);
	    fprintf(PMlog,"AT: %s",(char *)[PMtime stringValue]);
	    fprintf(PMlog,"FROM: %s",(char *)[PMcaller stringValue]);
	    fprintf(PMlog,"OF: %s",(char *)[PMorg stringValue]);
	    fprintf(PMlog,"NUMBER: %s",(char *)[PMnumber stringValue]);
	    for (i=0 ; i<ncol ; i++)
	      for (j=0 ; j<nrow ; j++)
	        if([[PMchecked cellAt:j :i] state])
	          fprintf(PMlog,"%s\n",[[PMchecked cellAt:j :i] title]);
	    fprintf(PMlog,"%s\n",msg);
	    fprintf(PMlog,"SIGNED: %s\n\n",[PMsigned stringValue]);
	    fclose(PMlog);
	  }
	  else
	    NXRunAlertPanel("PhoneSlip","Unable to open PhoneSlip log, check permissions", "Sorry", NULL, NULL);
	}
	     
	 
/*
	Reset PhoneSlip fields
*/
	[self cancel:self];
/*
	play the acknowledge sound
*/
	[[Sound findSoundFor:[PMsoundname stringValue]] play];
/*
	hide PhoneSlip
*/
	[NXApp hide:self];
	
	return self;
}

- cancel:sender
{
	int i, j, ncol, nrow;

/*
	Reset PhoneSlip fields
*/
	[PMfor setStringValue:""];
	[PMcaller setStringValue:""];
	[PMorg setStringValue:""];
	[PMnumber setStringValue:""];
	[PMchecked getNumRows:&nrow numCols:&ncol];
	for (i=0 ; i<ncol ; i++)
	  for (j=0 ; j<nrow ; j++)
	    [[PMchecked cellAt:j :i] setState:NO];
	[[PMchecked cellAt:0 :0] setState:YES];
	[PMchecked display];
	[[PMmsg docView] selectAll:self];
	[[PMmsg docView] replaceSel:"NO MESSAGE"];

	return self;
}

- (int)browser:sender fillMatrix:matrix inColumn:(int)column
{
/*
	Load addressee browser
*/
	FILE *People;
	char	buf[80];
	int	row;
	id	cell;

	row = 0;
	strcpy(peoplefile,[PMpeople stringValue]);
	if (strlen(peoplefile) == 0)
	{
	  strncpy(peoplefile,NXArgv[0],255);
          *rindex(peoplefile,'/') = 0; 
          strcat(peoplefile,"/people");
	}
	if ((People = (FILE *)fopen(peoplefile,"r")) != NULL)
	{
	  while (!feof(People))
	  {
	    fgets(buf,79,People);
	    [matrix addRow];
	    cell = [matrix cellAt: row  :0];	
	    [cell setStringValue:buf];
	    [cell setLoaded:YES];
	    [cell setLeaf:YES];
	    row++;
	  }

	  fclose(People);
	}
	else
	{
	  NXRunAlertPanel("PhoneSlip","NO PEOPLE FILE FOUND", "RETRY", "FAIL", "ABORT");
	}

	[PMbrowser setEnabled:YES];
	return row-1;
}

- setFor
{
		
/*
	set the addresse field from the currently selected browser line
*/
	[PMfor setStringValue:[[[PMbrowser matrixInColumn:0] selectedCell] stringValue]];
	[PMcaller selectText:self];

/*
	Reset Time
*/
	time(&tp);
	[PMtime setStringValue:asctime(localtime(&tp))];
	return self;
}

- setPeople:sender
{
/*
	Reset the people file name and reload the browser
*/
	const char *peoplepref;
	
	peoplepref = [PMpeople stringValue];
	if (strlen(peoplepref))
	{
	  (strcpy(peoplefile,peoplepref));
	  [PMbrowser loadColumnZero];
	  NXWriteDefault("PhoneSlip","People",peoplefile);
	}
	
	return self;
}

- setLogMailname:sender
{
/*
	Reset the log file name
*/
	const char *logpref;

	
	logpref = [PMlogmail stringValue];
	if(strlen(logpref))
	{
	  strcpy(logmailname,logpref);
	  NXWriteDefault("PhoneSlip","LogMailname",logmailname);
	}
	
	return self;
}

- setLogFilename:sender
{
/*
	Reset the log file name
*/
	const char *logpref;

	
	logpref = [PMlogfile stringValue];
	if(strlen(logpref))
	{
	  strcpy(logfilename,logpref);
	  NXWriteDefault("PhoneSlip","LogFilename",logfilename);
	}
	
	return self;
}

- setCheck:sender
{
	int col,row;
	
	col = [PMusercheck selectedCol]; 
	row = [PMusercheck selectedRow]; 
	temp = [[PMusercheck selectedCell] stringValue];
	[[PMchecked cellAt:row :col] setTitle:temp];
	sprintf(&checkname[5],"%1d%1d",col,row);
	NXWriteDefault("PhoneSlip",checkname,temp);
	return self;
}

- setSoundname:sender
{
	temp = [PMsoundname stringValue];
	strcpy(soundname,temp);
	[[Sound findSoundFor:soundname] play];
	NXWriteDefault("PhoneSlip","Soundname", soundname);
	return self;
}


@end
